23. Exercise: Navigate on Click

L7 39 Navigate On Click SC

Now it’s your turn to complete this exercise yourself!

In this exercise you'll change your listener to navigate to a new fragment and pass the data.

  1. **Open fragment_sleep_detail.xml and uncomment the code inside the ConstraintLayout.


  2. In SleepTrackerFragment, update the SleepNightListener code to pass the data to view model.

    val adapter = SleepNightAdapter(SleepNightListener {
        nightId ->  sleepTrackerViewModel.onSleepNightClicked(nightId)
    })


  3. In SleepTrackerViewModel, add a handler for the click event.

    You also need to add a MutableLiveData object to control the navigation.

    private val _navigateToSleepDataQuality = MutableLiveData<Long>()
    val navigateToSleepDataQuality
       get() = _navigateToSleepDataQuality


  4. Define method to initiate and complete naviattion.

    Initiate navigation by setting _navigateToSleepDataQuality.value to id:

    fun onSleepNightClicked(id: Long){
        _navigateToSleepDataQuality.value = id
    }

    and then set it to null once navigation is completed:

    fun onSleepDataQualityNavigated() {
        _navigateToSleepDataQuality.value = null
    }


  5. In SleepTrackerFragment, add an observer to trigger navigation when the listener passes the data to ViewModel.

    Make sure you call onSleepDataQualityNavigated when navigation is complete.

    sleepTrackerViewModel.navigateToSleepDataQuality.observe(this, Observer {night ->
          night?.let {
             this.findNavController().navigate(SleepTrackerFragmentDirections
                             .actionSleepTrackerFragmentToSleepDetailFragment(night))
             sleepTrackerViewModel.onSleepDataQualityNavigated()
          }
    })


If you want to start at this step, you can download this exercise from: Step.12-Exercise-Navigate-on-Click.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.12-Solution-Navigate-on-Click, or using this git diff.

Task Description:

Complete these tasks to navigate to a new fragment and pass data.

Task List:

Task Feedback:

Congratulations, you now have a working RecyclerView with navigation!